package com.sea.app.module.process.domain.service;

import com.sea.app.common.Entity.Page;
import com.sea.app.common.excrption.BusinessException;
import com.sea.app.module.process.controller.result.TaskResult;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by 31417 on 2017/5/2.
 */
@Service
public class ActivitiTaskService {
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;

    public Page<TaskResult> todo(String uid, List<String> groups, Page<TaskResult> page){
        TaskQuery todoTaskQuery = taskService.createTaskQuery().or();
        if(uid!=null){
            todoTaskQuery.taskCandidateUser(uid);
            todoTaskQuery.taskAssignee(uid);
        }
        if(groups!=null&&!groups.isEmpty()){
            todoTaskQuery.taskCandidateGroupIn(groups);
        }
        List<Task> list = todoTaskQuery.listPage(page.limitStart(),page.limitEnd());
        List<TaskResult> resultTasks = list.stream().map(task -> new TaskResult(task)).collect(Collectors.toList());
        return page.setCount(todoTaskQuery.count()).setList(resultTasks);
    }

    /**
     * 完成任务
     * @param taskId
     * @param comment
     * @param vars
     */
    public void complete(String taskId,String userId, String comment,Map<String, Object> vars){
        Authentication.setAuthenticatedUserId(userId);
        Task task = taskService.createTaskQuery()
                .taskId(taskId).singleResult();
        if(task == null){
            throw BusinessException.on("task.taskNotFind","没有发现任务！");
        }
        //添加意见
        if(comment!=null) {
            taskService.addComment(taskId, task.getProcessInstanceId(), comment);
        }

        // 提交任务
        taskService.complete(taskId, vars);
    }

    /**
     *获取审批历史
     * @param processInstanceId
     * @return
     */
    public List<HistoricActivityInstance>  processHistoricList(String processInstanceId){
        List<HistoricActivityInstance> list = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .list();
        return list;
    }



}
